//
//  CZUserAccount.swift
//  swiftweibo
//
//  Created by Apple on 15/11/25.
//  Copyright © 2015年 tzw. All rights reserved.
//

import UIKit
// 将对象归档到沙盒中
class CZUserAccount: NSObject,NSCoding {
    ///  用户是否登录
    class var userLogin:Bool {
        get{
          return CZUserAccount.loadUserAccount() != nil
        }
    }
    var access_token: String?
    // 过期时间
    var expires_in: NSTimeInterval = 0 {
        didSet{
            //设置过期的时间
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    // 当前用户授权的id
    var uid: String?
    // 保存过期时间
    var expiresDate: NSDate?
    // 用户昵称
    var screen_name: String?
    // avatar_large	string	用户头像地址（大图），180×180像素
    var avatar_large: String?
    // 字典转模型
    init(dict:[String : AnyObject]) {
        super.init()
        // 利用kvc来转模型
        setValuesForKeysWithDictionary(dict)
        print("\(dict)")
    }
    // MARK: - 加载用户信息
    func loadUserInfo(){
        CZNetworkTool.sharedInstance.loadUserInfo { (result, error) -> () in
            if error != nil && result == nil{
                print("数据加载失败")
                return
            }
            // 保存数据 
//            print("数据加载成功\(result)")
            self.screen_name = result!["screen_name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            // 更新账户
            CZUserAccount.userAccount = self
            // 保存数据
            self.saveAccount()
            
        }
        
    }
    
    // 保存路径
    static let plistPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
    // 将数据保存到沙盒中
    func saveAccount(){
        // 归档当前类
        NSKeyedArchiver.archiveRootObject(self, toFile: CZUserAccount.plistPath)
//        print("\(expiresDate)")
//        print("\(NSDate())")
        
    }
    // 定义一个内存中的账户
    private static var userAccount: CZUserAccount?
    // 读取保存在沙盒中的信息
    class func loadUserAccount()->CZUserAccount?{
        // 判断内存中的是否有值 
        if userAccount == nil{
            // 内存中没有值，去解档
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(plistPath) as? CZUserAccount
            
//            print("从沙盒中读取")
        }else
        {
//            print("从内存中读取")
        }
        // 解档判断当前的账号是否过期
//        print("\(userAccount)")
            // 判断是否过期
            if userAccount != nil && userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
//            print("没有过期")
                return userAccount
            }

        return nil
    }

    // 解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        
    }
    // 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    // 当KVC字典的key在模型中找不到对象时调用
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    // 打印对象信息
    override var description: String {
        return "access_token: \(access_token), expires_in:\(expires_in), uid = \(uid), expiresDate:\(expiresDate)"
    }

}
